#pragma once

#include<iostream>
#include<string>
#include<functional>
#include<pthread.h>
using namespace std;

namespace ThreadModule
{
    using func_t = function<void()>;
    static int number = 1;

    enum TSTATUS
    {
        NEW,
        RUNNING,
        STOP
    };

    class Thread
    {
    private:
        static void* Routine(void* args)
        {
            Thread* t = static_cast<Thread*>(args);
            t->_func();
            return nullptr;
        }
        void EnableDetach()
        {
            _joinable = false;
        }
    public:
        Thread(func_t func):_func(func), _status(TSTATUS::NEW),_joinable(true)
        {
            _name = "Thread-"+ to_string(number++);
        }
        bool Start()
        {
            if(_status != TSTATUS::RUNNING)
            {
                int n = pthread_create(&_tid,nullptr, Routine, this);
                if (n != 0) return false;
                _status = RUNNING;
                return true;
            }
            return false;
        }
        void Stop()
        {
            if(_status == RUNNING)
            {
                int n = pthread_cancel(_tid);
                if(n != 0)  return;
                _status = STOP;
            }
        }
        bool Join()
        {
            if(_joinable)
            {
                int n = pthread_join(_tid,nullptr);
                if(n != 0) return false;
                _status = STOP;
                return true;
            }
            return false;
        }
        void Detach()
        {
            EnableDetach();
            pthread_detach(_tid);
        }
        
        bool Isjoinable()
        {
            return _joinable;
        }
        string Name()
        {
            return _name;
        }
        ~Thread()
        {}
    private:
        string _name;
        pthread_t _tid;
        pid_t _pid;
        bool _joinable; // 是否是线程分离的
        func_t _func;
        enum TSTATUS _status;
    };

}